<?php

namespace app\store\controller\finance;

use app\store\controller\Controller;
use app\common\model\GetTui as GetTuiModel;

/**
 * 提现管理
 * Class autolits
 * @package app\store\controller
 */
class Cashwithdrawal extends Controller
{
    public function index() {
        $where = [];
		$newwhere = '';
		$name = $this->request->param("name/s" , '');
		if( $name ) {
			$newwhere = "u.nickname = '{$name}' OR u.user_id = '{$name}'";
		}
		$type = $this->request->param("type/s" , '');
		if( $type ) {
			$where['mw.type'] = $type;
		}
		$status = $this->request->param("status/d" , '');
		if( $status != '' ) {
			$where['mw.status'] = $status;
		}
        $list = db("member_withdrawcash")->alias("mw")->join("yoshop_user u","u.user_id = mw.user_id")->where($newwhere)->field("mw.*,u.nickname,u.avatar,u.mobile")->order('status ASC,id DESC')->where($where)->paginate(15, false, ['query' => $this->request->request()])->each(function($item , $key){
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
            return $item;
        });
        return $this->fetch('', compact('list'));
    }
	
	public function show() {
		$id = $this->request->param("id/d" , 0);
		if($id <= 0) exit("数据信息错误");
		$info = db("member_withdrawcash")->alias("mw")->join("yoshop_user u","u.user_id = mw.user_id")->field("mw.*,u.nickname,u.avatar")->where(['id' => $id])->find();
		if( !$info ) exit("信息不存在");
		if( request()->isPost() ) {
			$status = $this->request->param("status");
			if( !$status ) $this->error("请选择审核状态");
			$note = $this->request->param("note");
			if( $status == 1 && !$note ) $this->error("请输入要审核失败的原因");
			$result = db("member_withdrawcash")->where(['id' => $id])->update(['status' => $status , 'note' => $note]);
			if( $result ) {
				$userinfo = db("user")->where(['user_id' => $info['user_id']])->find();
				if( $userinfo ) {
					$obj = new  GetTuiModel;
					if( $status == 2 ) {
						$obj->sendToClient($info['user_id'] , '感恩奖励提示' , '您申请提现的金额【'.$info['money'].'】平台方已通过转账的方式到您的【'.$info['type'].'】账户中，请核对。' . ($note ? "备注；{$note}" : ''));
						
						//增加感恩奖
						$reward_user = $info['reward_user'] ? json_decode( $info['reward_user'] , true ) : '';
						if( $reward_user ) {
							foreach( $reward_user as $k => $v ) {
								//判断获奖用户是否存在
								$reward_user_info = db("user")->where(['user_id' => $v])->find();
								if( $reward_user_info ) {
									$obj->sendToClient($v , '感恩奖励提示' , '您的好友【'.$userinfo['nickname'].'】提现获得感恩奖【'.$info['reward_price'].'】积分');
									db("user")->where(['user_id' => $v])->update(['integral' => $reward_user_info['integral'] + $info['reward_price']]);
									db("member_cart_order_distribution")->insert([
										'user_id' => $v,
										'type' => 5,
										'status' => 1,
										'price' => $info['reward_price'],
										'ordersn' => '-',
										'member_cart_order_id' => 0,
										'create_time' => time()
									]);
									db("user_integral_log")->insert([
										'user_id' => $v,
										'num' => $info['reward_price'],
										'type' => 1,
										'content' => '您的好友【'.$userinfo['nickname'].'】提现获得感恩奖【'.$info['reward_price'].'】积分',
										'create_time' => time()
									]);
								}
							}
						}
						//增加用户提现总金额
						db("user")->where(['user_id' => $userinfo['user_id']])->update(['tx_total_price' => $userinfo['tx_total_price'] + $info['money'],'tx_integral' => $userinfo['tx_integral'] + $info['money']]);
					} else {
						$obj->sendToClient($info['user_id'] , '提现审核状态消息' , '您申请提现的积分【'.$info['money'].'】平台审核未通过，金额已返回至您的积分账户中。请查看。' . ($note ? "备注；{$note}" : ''));
						db("user")->where(['user_id' => $info['user_id']])->update(['integral' => $userinfo['integral'] + $info['money']]);
						db("user_integral_log")->insert([
							'user_id' => $info['user_id'],
							'num' => $info['money'],
							'type' => 1,
							'content' => '申请提现积分平台审核失败，积分【'.$info['money'].'】原路退回至本地账户',
							'create_time' => time()
						]);
					}
				}
				$this->success("审核操作成功" , url('store/finance.cashwithdrawal/index'));
			} else {
				$this->error("操作失败");
			}
		} else {
			$template_type = 'tips';
			return $this->fetch('' , compact('info' , 'template_type'));
		}
	}
	
	public function delete() {
		$id = $this->request->param("id/d" , 0);
		if($id <= 0) exit("数据信息错误");
		$info = db("member_withdrawcash")->alias("mw")->join("yoshop_user u","u.user_id = mw.user_id")->field("mw.*,u.nickname,u.avatar")->where(['id' => $id])->find();
		if( !$info ) exit("信息不存在");
		$result = db("member_withdrawcash")->where(['id' => $id])->delete();
		if($result) {
			$this->success("删除成功");
		} else {
			$this->error("操作失败");
		}
	}
	
	public function export()
    {
		$where = [];
		$newwhere = '';
		$name = $this->request->param("name/s" , '');
		if( $name ) {
			$newwhere = "u.nickname = '{$name}' OR u.user_id = '{$name}'";
		}
		$type = $this->request->param("type/s" , '');
		if( $type ) {
			$where['mw.type'] = $type;
		}
		$status = $this->request->param("status/d" , '');
		if( $status != '' ) {
			$where['mw.status'] = $status;
		}
        $list = db("member_withdrawcash")->alias("mw")->join("yoshop_user u","u.user_id = mw.user_id")->where($newwhere)->field("mw.*,u.nickname,u.avatar,u.mobile")->order('status ASC,id DESC')->where($where)->select()->each(function($item , $key){
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
            return $item;
        })->toArray();
		$new_data = [];
		if( $list ){
			foreach( $list as $k => $v ) {
				$reward_user = $v['reward_user'] ? json_decode( $v['reward_user'] , true ) : [];
				$new_data[] = [
					'id' => $v['id'],
					'nickname' => $v['nickname'],
					'mobile' => $v['mobile'],
					'type' => $v['type'],
					'name' => $v['name'],
					'cart_no' => $v['cart_no'],
					'money' => $v['money'],
					'user_money' => $v['user_money'],
					'status' => $v['status'] == 0 ? '未审核' : ($v['status'] == 1 ? '审核未通过' : '已通过'),
					'create_time' => $v['create_time'],
					'reward_ratio' => $v['reward_ratio'] . "%",
					'reward_user' => count($reward_user),
					'num' => count($reward_user) * $v['reward_price'],
				];
			}
		}
		$field = ['ID' , '提现用户' , '联系方式' , '提现类型' , '机构名称' , '账号/卡号' , '提现积分' , '实际到账' , '状态' , '创建时间' , '分佣比例' , '分佣人数' , '分佣积分'];
		\app\common\extend\Excel::export($new_data , $field);
	}
}